import {createAsyncThunk} from '@reduxjs/toolkit';
import {
    createConservationAPI,
    deleteConservationAPI,
    updateConservationAPI,
    queryConservationAll,
    queryConservationDetail,
    queryConservationList,
} from '@/api/sapper/conservation';
import {
    ConservationUpdateReq,
    ConservationCreateReq,
    GetConservationListParam,
    GetAllConservationParam
} from "@/types/conservationType";
import {generateAnswerStream} from "@/api/sapper/agent";

// 获取所有会话
export const fetchAllConservations = createAsyncThunk(
    'conservation/fetchAllConservations',
    async (param: GetAllConservationParam, { rejectWithValue }) => {
        try {
            return await queryConservationAll(param);
        } catch (error: unknown) {
            if (typeof error === 'object' && error !== null && 'response' in error) {
                const err = error as { response: { data?: never } };
                if (err.response && 'data' in err.response) {
                    return rejectWithValue(err.response.data);
                }
            }
            return rejectWithValue('Failed to fetch all conservations');
        }
    }
);

// 获取会话详情
export const fetchConservationDetail = createAsyncThunk(
    'conservation/fetchConservationDetail',
    async (conservationUuid: string, { rejectWithValue }) => {
        try {
            return await queryConservationDetail(conservationUuid);
        } catch (error: unknown) {
            if (typeof error === 'object' && error !== null && 'response' in error) {
                const err = error as { response: { data?: never } };
                if (err.response && 'data' in err.response) {
                    return rejectWithValue(err.response.data);
                }
            }
            return rejectWithValue('Failed to fetch conservation details');
        }
    }
);

// 获取会话列表（分页）
export const fetchConservationList = createAsyncThunk(
    'conservation/fetchConservationList',
    async (params: GetConservationListParam | undefined, { rejectWithValue }) => {
        try {
            return await queryConservationList(params);
        } catch (error: unknown) {
            if (typeof error === 'object' && error !== null && 'response' in error) {
                const err = error as { response: { data?: never } };
                if (err.response && 'data' in err.response) {
                    return rejectWithValue(err.response.data);
                }
            }
            return rejectWithValue('Failed to fetch conservation list');
        }
    }
);


// 创建会话
export const createConservation = createAsyncThunk(
    'conservation/createNewConservation',
    async (data: ConservationCreateReq, { rejectWithValue }) => {
        try {
            return await createConservationAPI(data);
        } catch (error: unknown) {
            if (typeof error === 'object' && error !== null && 'response' in error) {
                const err = error as { response: { data?: never } };
                if (err.response && 'data' in err.response) {
                    return rejectWithValue(err.response.data);
                }
            }
            return rejectWithValue('Failed to create conservation');
        }
    }
);

// 更新会话
export const updateConservation = createAsyncThunk(
    'conservation/updateConservationInfo',
    async ({ conservationUuid, data }: { conservationUuid: string; data: ConservationUpdateReq }, { rejectWithValue }) => {
        try {
            return await updateConservationAPI(conservationUuid, data);
        } catch (error: unknown) {
            if (typeof error === 'object' && error !== null && 'response' in error) {
                const err = error as { response: { data?: never } };
                if (err.response && 'data' in err.response) {
                    return rejectWithValue(err.response.data);
                }
            }
            return rejectWithValue('Failed to update conservation');
        }
    }
);


// 批量删除会话
export const deleteConservation = createAsyncThunk(
    'conservation/deleteConservations',
    async (pk: string, { rejectWithValue }) => {
        try {
            await deleteConservationAPI(pk);
            return pk
        } catch (error: unknown) {
            if (typeof error === 'object' && error !== null && 'response' in error) {
                const err = error as { response: { data?: never } };
                if (err.response && 'data' in err.response) {
                    return rejectWithValue(err.response.data);
                }
            }
            return rejectWithValue('Failed to delete conservations');
        }
    }
);


export const generateAnswer = createAsyncThunk(
  'conservation/generateAnswer',
  async ({ uuid, data }: { uuid: string; data: {} }, { dispatch }) => {
    // 创建WebSocket连接
    const task = await generateAnswerStream(uuid)

    new Promise((resolve, reject) => {
      // 连接成功回调
      task.onOpen(() => {
        console.log('WebSocket connected');

        // 发送初始数据
        task.send({
          data: JSON.stringify(data),
          success: () => {
            console.log('Initial data sent');
          },
          fail: (err) => {
            reject(err.errMsg);
            task.close({ reason: 'Send failed' });
          }
        });
      });

      // 消息接收处理
      task.onMessage((msg: any) => {
        try {
          const result = msg.data;
          if (result) {
            const parsed = JSON.parse(result);
            dispatch({
              type: 'conservation/setConservationAnswerInfo',
              payload: [parsed]
            });
          }
        } catch (e) {
          console.error('Message processing error:', e);
          task.close({ reason: 'Parse error' });
          reject(e);
        }
      });

      // 错误处理
      task.onError((error: any) => {
        console.error('WebSocket error:', error);
        task.close({ reason: 'Error occurred' });
        reject(error.errMsg || 'Connection error');
      });

      // 连接关闭处理
      task.onClose((e: any) => {
        console.log('Connection closed:', e);
        dispatch({
          type: 'conservation/setConservationStateInfo',
          payload: {generating: false}
        });
        if (e.code !== 1000) {
          reject(new Error(`Closed with code ${e.code}: ${e.reason}`));
        } else {
                                                                                                                                                                                                                                                                                                                                                                                                                                                 resolve({ success: true });
        }
      });
    }).finally(() => {
      // 确保关闭连接
      if (task.readyState === task.OPEN) {
        task.close({ reason: 'Process completed' });
      }
    });

    return task
  }
);
